package com.opgea.crm.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.common.vo.LeadDocumentsVo;
import com.opgea.crm.domain.entities.Lead;
import com.opgea.crm.domain.entities.LeadDocuments;
import com.opgea.crm.domain.modal.FileUploadBean;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.LeadDocumentService;
import com.opgea.crm.services.LeadService;
import com.opgea.crm.web.modal.LoggedUser;

@Controller
@RequestMapping(value="documents")
public class DocumentController {

	private static final String FILE_UPLOAD_SUCCESS_RESPONSE = 
		"{\"success\":%s,\"message\":\"%s\",\"fileData\":{\"size\":%s," +
		" \"name\":\"%s\", \"type\":\"%s\"}}";
	
	
	@Autowired
	LeadService leadService;
	@Autowired
	EmployeeService employeeService;
	@Autowired
	LeadDocumentService leadDocumentService;

	
	protected String buildSuccessFileUploadResonse(String message, long fileSize, String fileName, String fileType){
		return String.format(FILE_UPLOAD_SUCCESS_RESPONSE, Boolean.TRUE, message,fileSize,fileName,fileType);
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = "uploadDocument")
	public String uploadDocument(	@RequestParam(value="leadId") long leadId,
												@RequestParam(value="receiveDate")String receiveDate,
								 				FileUploadBean fileUploadBean,
								 				HttpServletRequest request,
								 				HttpServletResponse response)throws IOException{
		
		System.out.println("Document Controller >> uploadDocument >> LeadId : "+leadId);
		Lead lead = leadService.findLead(leadId);
		
		
		MultipartFile multipartFile = fileUploadBean.getFile();
		System.out.println("filename : "+multipartFile.getOriginalFilename());
		System.out.println("lead : "+lead);
		
		LeadDocuments doc = new LeadDocuments();
		doc.setDocumentType(fileUploadBean.getDocumentTypeId());
		doc.setDocumentName(fileUploadBean.getDocumentName());
		doc.setFileName(multipartFile.getOriginalFilename());
		doc.setFileSize(multipartFile.getSize());
		doc.setContent(multipartFile.getBytes());
		doc.setLead(lead);
		System.out.println("Receive Date : "+receiveDate);
		doc.setReceiveDate(DateUtil.stringToDate(receiveDate));		
		
		doc.setSenderName(LoggedUser.getUser(request).getUserName());
		doc.setCreatedAt(new Date());
		doc.setCreatedBy(LoggedUser.getUser(request));
		
		
		System.out.println("Document Uploaded : "+multipartFile.getOriginalFilename());
		leadDocumentService.create(doc);
		
		
		response.setContentType("text/html");
		HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
		Writer out = responseWrapper.getWriter();
		String json = buildSuccessFileUploadResonse("File uploaded Successfully", 
										fileUploadBean.getFile().getSize(),
										fileUploadBean.getFile().getOriginalFilename(),
										fileUploadBean.getFile().getContentType());
		out.write(json);
		out.close();
		
		System.out.println("Success");
		
		return null;
    }
	
	
	@RequestMapping(method = RequestMethod.GET, value = "viewDocument")
	public Map<String,Object> viewDocumen(HttpServletResponse response) throws IOException{
		
		System.out.println("inside view document controller");
		//LeadDocuments doc = new LeadDocuments();
		
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition","attachment; filename=test.doc");
		
		StringBuffer sb = new StringBuffer("TESTING");
		InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
		BufferedInputStream bis = new BufferedInputStream(in);
		BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
	
		 
		byte[] outputByte = new byte[4096];
		//copy binary contect to output stream
		int a ;
		while( (a = bis.read()) != -1)
		{
			bos.write(a);
		}
		in.close();
		bos.flush();
		bos.close();
		
		return null;
	}
	
	
	@RequestMapping(method = RequestMethod.GET, value = "docList")
	public @ResponseBody
	Map<String, Object> documentList(@RequestParam(required=false, value="leadId")String leadId) {
		System.out.println("Document Controllert >> docList "+leadId);
		if(leadId != null){
			List<LeadDocumentsVo> docs = leadDocumentService.findAllByLead(new Long(leadId));
			if(docs != null){
				return JsonModelMap.success().data(docs);
			}else{
				return JsonModelMap.success();
			}
		}else{
			return JsonModelMap.success();
		}
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "viewDoc")
	public @ResponseBody
	void viewDoc(HttpServletResponse response)throws IOException {
		
		ServletOutputStream stream = null;
		BufferedInputStream buf = null;
		try {
			stream=response.getOutputStream();
		//List<LeadDocumentsVo> docs = leadDocumentService.findAllByLead(1313);
		response.setContentType("application/msword");
		response.setDateHeader("Expires", 0);
		response.addHeader("Content-Disposition","attachment; filename=test.doc");
		String str="Mritunjay Prasad Singh";
		stream.write(str.getBytes());
	} 
		
		finally {
		if (stream != null)
			stream.flush();
		stream.close();
		if (buf != null)
			buf.close();
	}
		
	}
    
}
